package com.cheetah.solr.web;

import com.cheetah.solr.entity.Position;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.SimpleQuery;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/position")
public class PositionController {

    private SolrTemplate solrTemplate;
    private SolrClient solrClient;

    @Autowired
    public void setSolrClient(SolrClient solrClient) {
        this.solrClient = solrClient;
        this.solrTemplate = new SolrTemplate(solrClient);
        this.solrTemplate.afterPropertiesSet();
    }

    @RequestMapping("/search")
    public Object search(String name,
             @RequestParam(required = false, defaultValue = "5") int rows) throws Exception {
        Page page = this.solrTemplate.query("new_core",
                new SimpleQuery("positionName:" + name), Position.class);
        long total = page.getTotalElements();
        if (total >= rows) {
            return page.getContent();
        }
        List list = new ArrayList(page.getContent());
        int num = rows - list.size();
        Page other = this.solrTemplate.query("new_core",
                new SimpleQuery("positionAdvantage:美女").setRows(num), Position.class);
        list.addAll(other.getContent());
        return list;
    }

    /**
     * solr client代码演示
     * @param rows
     * @param name
     * @return
     * @throws Exception
     */
    Object clientSearch(int rows, String name) throws Exception {
        QueryResponse resp = this.solrClient
                .query("new_core",
                        new SolrQuery().setQuery("positionName:" + name));
        long found = resp.getResults().getNumFound();
        if (found >= rows) {
            return resp.getBeans(Position.class);
        }
        List list = resp.getBeans(Position.class);
        int num = rows - list.size();
        resp = this.solrClient.query("new_core",
                new SolrQuery().setQuery("positionAdvantage:美女").setRows(num));
        list.addAll(resp.getBeans(Position.class));
        return list;
    }
}
